﻿// ===============================================================================
// DotNet.Platform 开发框架 2016 版权所有
// ===============================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
using DotNet.Utility;

namespace DotNet.Helper
{
    public static class EntityHelper
    {
        /// <summary>
        /// 验证对象是否有效
        /// </summary>
        /// <param name="entity">要验证的对象。</param>
        /// <returns>如果对象有效，则为 true；否则为 false。</returns>
        public static bool IsValid(object entity)
        {
            var context = new ValidationContext(entity);
            var results = new List<ValidationResult>();

            return Validator.TryValidateObject(entity, context, results, true);
        }

        public static IEnumerable<ValidationResult> Valid(object entity)
        {
            var context = new ValidationContext(entity);
            var results = new List<ValidationResult>();

            Validator.TryValidateObject(entity, context, results, true);
            return results;
        }

        public static BoolMessage ValidAsMessage(object entity, string separator = "\r\n")
        {
            var result = BoolMessage.True;
            var context = new ValidationContext(entity);
            var results = new List<ValidationResult>();

            Validator.TryValidateObject(entity, context, results, true);
            if (results.Count > 0)
            {
                StringBuilder sb = new StringBuilder();
                results.ForEach(p =>
                {
                    sb.Append($"{p.ErrorMessage}{separator}");
                });
                result = new BoolMessage(false, sb.ToString());
            }
            return result;
        }
    }
}